<template>
  <div style="width:100vw;display:flex;justify-content: center;background:#F9F9F9">
    <div class="container" style="width: 75vw;padding:0px 20px 40px 20px;padding-top: 0px;">
      <!-- 详细分析 -->
      <div class="content-section">
        <div class="section-header">
          <p class="section-title">
            详细分析
          </p>
        </div>
        <transition name="slide">
          <div class="analysis-section" v-show="isSectionVisible.detail">
            <el-table 
              :data="questionData" 
              border 
              style="width: 100%"
              row-key="id"
              @expand-change="handleExpand"
              ref="questionTable"
            >
              <!-- 展开列 -->
              <el-table-column type="expand" width="60">
                <template #header>
                  <span 
                    @click.stop="toggleAllExpansion"
                    style="cursor: pointer;color:#007bff"
                  >
                    {{ isAllExpanded? '收起' : '展开' }}
                  </span>
                </template>
                <template #default="{ row }">
                  <div class="detail-card">
                    <div class="detail-left">
                      <p class="sub-title">{{ row.type === '简答题'? '学生回答' : '选项内容' }}</p>
                      <template v-if="row.type!== '简答题'">
                        <ul>
                          <li 
                            v-for="option in row.options" 
                            :key="option.option_id"
                          >
                            {{ getOptionLabel(row.options.indexOf(option)) }}. {{ option.option_content }}
                            <span class="answer-count" style="color: #28a745;">({{ option.choose_cnt || 0 }}人，{{ (option.choose_percent * 100).toFixed(0) }}%)</span>
                          </li>
                        </ul>
                      </template>
                      <div v-else class="answer-list" style="padding:10px 0;">
                        <div v-for="(answer, index) in row.qnaLevels" :key="index" class="student-answer">
                          <p class="answer-text">{{ answer.stu_ans || '-' }}</p>
                        </div>
                      </div>
                      <div class="answer-tip">
                        <span>答题人数：</span><span style="color: #28a745;">{{ row.answered || 0 }}</span>
                      </div>
                    </div>
                    <div v-if="row.type!== '简答题'" class="detail-right">
                      <p class="sub-title" style="color: #007bff;">答题情况</p>
                      <el-table :data="row.answers" border size="small">
                        <el-table-column prop="option" label="选项" width="45" align="center"/>
                        <el-table-column prop="count" label="人数" width="45" align="center"/>
                        <el-table-column label="比例" align="center">
                          <template #default="{ row }">
                            <el-progress :percentage="row.percentage * 100" :stroke-width="12"/>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </div>
                </template>
              </el-table-column>

              <!-- 常规列 -->
              <el-table-column type="index" label="题号" width="60" align="center" :index="indexMethod"/>
              <el-table-column prop="content" label="题目内容" min-width="200">
                <template #default="{ row }">
                  {{ stripTags(row.content) }}
                </template>
              </el-table-column>
              <el-table-column prop="type" label="题型" width="100" align="center"/>
              <el-table-column prop="answered" label="已答" width="80" align="center"/>
              <el-table-column prop="unanswered" label="未答" width="80" align="center"/>
              <el-table-column prop="total" label="总数" width="80" align="center"/>
            </el-table>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue';
import { fetchSurveyAnalysis } from '@/services/api';
import { useRoute } from 'vue-router';

export default {
  setup() {
    // 数据相关
    const questionData = ref(null);
    const route = useRoute();
    const expandedRows = ref([]);
    const isAllExpanded = ref(false);
    const isSectionVisible = ref({ detail: true });
    const questionTable = ref(null);

    // 辅助函数
    const stripTags = (html) => {
      const tmp = document.createElement("div");
      tmp.innerHTML = html;
      return tmp.textContent || tmp.innerText || "";
    };

    const indexMethod = (index) => index + 1;

    const getOptionLabel = (index) => {
      return String.fromCharCode(65 + index); // 65是ASCII码中'A'的值
    };

    // 数据处理函数
    const processData = (apiData) => {
      if (!apiData ||!apiData.length) return [];

      const processedData = [];

      // 处理选择题
      const choiceQuestions = apiData[0] || [];
      choiceQuestions.forEach((item, index) => {
        const totalAnswered = item.options.reduce((sum, option) => sum + (option.choose_cnt || 0), 0);
        const totalParticipants = totalAnswered > 0? totalAnswered : 1;
        const unanswered = totalParticipants - totalAnswered;

        const answers = item.options.map(option => ({
          option: getOptionLabel(item.options.indexOf(option)),
          text: option.option_content,
          count: option.choose_cnt || 0,
          percentage: option.choose_percent || 0
        }));

        const correctOption = item.options[0] || {};
        const accuracy = ((correctOption.choose_cnt || 0) / totalParticipants * 100).toFixed(1) + '%';
        const totalScore = item.options.length;
        const obtainedScore = item.options.reduce((score, option) => {
          return score + (option.choose_cnt || 0);
        }, 0);
        const scoreRate = (obtainedScore / (totalParticipants * totalScore) * 100).toFixed(1) + '%';

        processedData.push({
          id: `q${index + 1}`,
          content: item.qs_title,
          type: '选择题',
          options: item.options,
          answers,
          answered: totalAnswered,
          unanswered,
          total: totalParticipants,
          accuracy,
          scoreRate
        });
      });

      // 处理简答题
      const shortAnswerQuestions = apiData[1] || [];
      shortAnswerQuestions.forEach((item, index) => {
        const choiceIndex = choiceQuestions.length;
        const qnaLevels = item.qnaLevels || [];
        const totalParticipants = qnaLevels.length;
        const unanswered = 0;

        const accuracy = '-';
        const scoreRate = '-';

        processedData.push({
          id: `q${choiceIndex + index + 1}`,
          content: item.qs_title,
          type: '简答题',
          qnaLevels,
          answered: totalParticipants,
          unanswered,
          total: totalParticipants,
          accuracy,
          scoreRate
        });
      });

      return processedData;
    };

    // 数据加载函数
    const loadData = async () => {
      try {
        const semesterId = Number(route.params.semesterId);
        const surveyId = Number(route.params.surveyId);
        const response = await fetchSurveyAnalysis(semesterId, surveyId);
        if (response.data.status === 1) {
          questionData.value = processData(response.data.data);
          
          // 默认展开第一行
          nextTick(() => {
            if (questionData.value.length > 0) {
              questionTable.value.toggleRowExpansion(questionData.value[0], true);
            }
          });
        }
      } catch (error) {
        console.error("数据加载失败：", error);
      }
    };

    // 展开/收起事件处理函数
    const handleExpand = (row, expandedRows) => {
      isAllExpanded.value = expandedRows.length === questionData.value.length;
    };
    // 全部展开/收起函数
   const toggleAllExpansion = () => {
      isAllExpanded.value =!isAllExpanded.value;
      questionData.value.forEach(row => {
        questionTable.value.toggleRowExpansion(row, isAllExpanded.value);
      });
    };

    // 切换内容区域显示状态
    const toggleSection = (section) => {
      isSectionVisible.value[section] =!isSectionVisible.value[section];
    };

    onMounted(() => {
      loadData();
    });

    return {
      questionData,
      expandedRows,
      isAllExpanded,
      isSectionVisible,
      questionTable,
      stripTags,
      indexMethod,
      getOptionLabel,
      processData,
      loadData,
      handleExpand,
      toggleAllExpansion,
      toggleSection
    };
  }
};
</script>

<style scoped>
.detail-card {
  display: flex;
  gap: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  margin: 10px 0;
}

.detail-left {
  flex: 7;
  padding: 0px 40px;
  border-right: 1px solid #eee;
}

.detail-right {
  flex: 3;
  padding: 0px 20px;
}

.sub-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
  font-weight: 500;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

li:last-child {
  border-bottom: none;
}

.correct-answer {
  color: #67C23A !important;
  font-weight: 500;
}

.answer-tip {
  display: flex;
  justify-content: flex-start;
  padding: 20px 0px;
}

.answer-tip span {
  font-weight: bold;
}

.answer-list {
  max-height: 200px;
  overflow-y: auto;
}

.student-answer {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.answer-text {
  line-height: 1.5;
}

.answer-count {
  float: right;
  color: #909399;
  font-size: 12px;
}

.content-section {
  background-color: #ffffff;
  padding: 20px 30px 0px;
  border-radius: 8px;
}

.analysis-section {
  padding: 15px;
}

.section-title{
    font-weight: 600;
    margin-bottom: 1rem;
    color: rgb(46, 46, 46);
}

.section-header {
  cursor: pointer;
  position: relative;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  transition: background 0.3s;
}

.arrow {
  display: inline-block;
  margin-left: 10px;
  border: solid #666;
  border-width: 0 2px 2px 0;
  padding: 3px;
  transform: rotate(45deg);
  transition: transform 0.3s;
}

.rotate {
  transform: rotate(-135deg);
}

/* 表格美化 */
.section-title {
  font-weight: bold;
  font-size: 18px;
  border-left: 4px solid #007bff;
  padding-left: 12px;
  margin-bottom: 15px;
}

/* 表格美化 */
.score-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  margin-top: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.score-table th, .score-table td {
  padding: 10px;
  text-align: center;
}

.score-table th {
  background-color: #5470C6;
  color: white;
  font-weight: bold;
}
</style>